import { NgModule, Optional, SkipSelf } from "@angular/core";
import { CommonModule } from "@angular/common";
import { httpInterceptorProviders } from "./http";
import { CanDeactivateGuard } from "./route/can-deactivate-guard";
import {
  ApplicationConfiguration,
  ApplicationService
} from "./application.service";
import { SelectivePreloadingStrategyService } from "./route/selective-preloading-strategy.service";
import { HttpErrorHandlerService } from "./http/http-error-handler.service";
import {
  RequestCache,
  RequestCacheWithMap
} from "./http/request-cache.service";

@NgModule({
  declarations: [],
  imports: [CommonModule],
  providers: [
    ApplicationService,
    HttpErrorHandlerService,
    httpInterceptorProviders,
    SelectivePreloadingStrategyService,
    CanDeactivateGuard,
    { provide: RequestCache, useClass: RequestCacheWithMap }
  ]
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() parentModule: CoreModule) {
    if (parentModule) {
      throw new Error("CoreModule is already loaded.");
    }
  }

  static forRoot(config: ApplicationConfiguration) {
    return {
      ngModule: CoreModule,
      providers: [{ provide: ApplicationConfiguration, useValue: config }]
    };
  }
}
